<?php

/**
 * @package Bike
 * @subpackage Events
 */

/**
 * Class for handling events
 * @author Chrome
 * @package Bike
 * @subpackage Events
 */
class Bike_Events_EventManager {
	/**
	 * Events storage
	 * @var array
	 */
	protected $events = array();

	/**
	 * Register event handler
	 * @param string $eventName
	 * @param string|Bike_Events_IEventHandler $eventHandler
	 * @return boolean
	 */
	public function register($eventName, $eventHandler){
		$this->events[$eventName][] = $eventHandler;
		return true;
	}

	/**
	 * Execute event handlers for event
	 * @param string $eventName
	 * @return boolean|mixed
	 */
	public function fireEvent($eventName){
		if(empty ($eventName) || empty($this->events[$eventName])){
			return false;
		}
		$result = null;
		foreach($this->events[$eventName] as &$eventHandler){
			if(is_string($eventHandler)){
				$eventHandler = new $eventHandler();
			}
			if($eventHandler instanceof Bike_Events_IEventHandler){
				$result = $eventHandler->handle();
			}
			if(!empty($result)){
				return $result;
			}
		}
		return false;
	}

	/**
	 * Return registered handlers
	 * @return array
	 */
	public function getRegisteredHandlers(){
		return $this->events;
	}

	/**
	 * Remove event handler for $eventName
	 * @param string $eventName
	 * @return boolean
	 */
	public function removeHandlers($eventName){
		if(empty($eventName) || empty($this->events[$eventName])){
			return false;
		}
		unset($this->events[$eventName]);
		return true;
	}

	/**
	 * Clean event handlers for all events
	 * @return boolean
	 */
	public function removeAllHandlers(){
		$this->events = array();
		return true;
	}
}
